package cn.com.lsy.product.lepao.controller;

import cn.com.lsy.product.lepao.common.Constant;
import cn.com.lsy.product.lepao.controller.base.BaseController;
import cn.com.lsy.product.lepao.model.entities.*;
import cn.com.lsy.product.lepao.model.mt.entities.UserListDto;
import cn.com.lsy.product.lepao.model.mt.entities.UserMonthCardDto;
import cn.com.lsy.product.lepao.request.*;
import cn.com.lsy.product.lepao.response.MonthCardTotalRet;
import cn.com.lsy.product.lepao.response.SearchUserInfoRet;
import cn.com.lsy.product.lepao.response.SearchUserListRet;
import cn.com.lsy.product.lepao.response.base.ApiResponseEnum;
import cn.com.lsy.product.lepao.response.base.BaseRet;
import cn.com.lsy.product.lepao.response.base.PageInfo;
import cn.com.lsy.product.lepao.service.IGoodsService;
import cn.com.lsy.product.lepao.service.ILoggerService;
import cn.com.lsy.product.lepao.service.IUserService;
import cn.com.lsy.product.lepao.util.CommonFunctionUtil;
import cn.com.lsy.product.lepao.util.DozerMapperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value = "用户管理接口", tags = "用户管理接口")
@RestController
@RequestMapping(value = "/lepao/console/doAuth")
public class UserController extends BaseController {

    private Logger log = Logger.getLogger(UserController.class);

    @Autowired
    IUserService iUserService;
    @Autowired
    IGoodsService iGoodsService;
    @Autowired
    ILoggerService iLoggerService;

    @RequestMapping(value = "/userList", method = RequestMethod.POST)
    @ApiOperation(notes = "用户列表", httpMethod = "POST", value = "用户列表")
    public BaseRet<PageInfo<List<SearchUserListRet>>> userList(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchUserListParam param, BindingResult result) {

        BaseRet<PageInfo<List<SearchUserListRet>>> ret = new BaseRet<PageInfo<List<SearchUserListRet>>>();

        PageInfo<List<SearchUserListRet>> pageInfo = new PageInfo<List<SearchUserListRet>>();

        try {

            checkParam(result);

            int count = iUserService.selectByCount(param.getStatus(), param.getStartTime(), param.getEndTime(), param.getSearchCondition(), param.getStoreId(), param.getCardType(), param.getCardState(), param.getSex());
            pageInfo.setCount(count);
            int start = param.getStart();

            List<UserListDto> list = iUserService.selectByPage(start, param.getPageSize(), param.getStatus(), param.getStartTime(), param.getEndTime(), param.getSearchCondition(), param.getStoreId(), param.getCardType(), param.getCardState(), param.getSex());

            List<SearchUserListRet> listRet = new ArrayList<SearchUserListRet>();

            if (list != null && list.size() > 0) {

                for (UserListDto value : list) {

                    SearchUserListRet searchUserListRet = DozerMapperUtil.map(value, SearchUserListRet.class);
                    //计算月卡剩余天数
                    if (value.getuEndTime() != null) {

                        long day = CommonFunctionUtil.calculateTime(value.getuEndTime());
                        if (day > 0) {
                            searchUserListRet.setMonthCard(day + "天");
                        } else {
                            searchUserListRet.setMonthCard("已过期");
                        }

                    } else {
                        searchUserListRet.setMonthCard("暂无月卡");
                    }

                    //扩展信息字段
                    if (StringUtils.isNotEmpty(value.getExt())) {

                        JSONObject ext = JSONObject.fromObject(value.getExt());
                        if (ext.has("lastStoreName")) {
                            searchUserListRet.setLastStoreName(ext.getString("lastStoreName"));
                        }
                        if (ext.has("lastEntTime")) {
                            searchUserListRet.setLastEntTime(ext.getString("lastEntTime"));
                        }
                        if (ext.has("totalEntNum")) {
                            searchUserListRet.setTotalEntNum(ext.getInt("totalEntNum"));
                        }
                        if (ext.has("monthEntNum")) {
                            searchUserListRet.setMonthEntNum(ext.getInt("monthEntNum"));
                        }
                        if (ext.has("isReceive")) {
                            searchUserListRet.setIsReceive(ext.getString("isReceive"));
                        } else {
                            searchUserListRet.setIsReceive("0");
                        }


                    } else {
                        searchUserListRet.setLastEntTime("");
                        searchUserListRet.setLastStoreName("");
                        searchUserListRet.setTotalEntNum(0);
                        searchUserListRet.setMonthEntNum(0);

                    }

                    //押金情况
                    if (value.getIsDepositFree() != null) {

                        if (value.getIsDepositFree().equals("0")) {
                            searchUserListRet.setDepositInfo("免押");
                        } else {

                            if (value.getDeposit().compareTo(BigDecimal.ZERO) <= 0) {
                                searchUserListRet.setDepositInfo("未交押金");
                            } else {
                                searchUserListRet.setDepositInfo(value.getDeposit() + "元");
                            }
                        }

                    } else {

                        searchUserListRet.setDepositInfo("未交押金");
                    }

                    searchUserListRet.setLoginType(CommonFunctionUtil.getUserSource(value.getLoginType()));

                    listRet.add(searchUserListRet);
                }
            }

            pageInfo.setRecords(listRet);

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(pageInfo);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/updateUserStatus", method = RequestMethod.POST)
    @ApiOperation(notes = "修改用户状态", httpMethod = "POST", value = "修改用户状态")
    public BaseRet<String> updateUserStatus(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody UpdateStatusParam param, BindingResult result) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);

            LpUserInfoTbl lpUserInfoTbl = new LpUserInfoTbl();
            lpUserInfoTbl.setId(param.getId());
            lpUserInfoTbl.setStatus(param.getStatus());

            if (iUserService.updateUserInfo(lpUserInfoTbl)) {

                ret.setMsg("修改成功");
                ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);

            } else {

                ret.setMsg("修改失败");
                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            }


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/userInfo", method = RequestMethod.POST)
    @ApiOperation(notes = "用户详情", httpMethod = "POST", value = "用户详情")
    public BaseRet<SearchUserInfoRet> userInfo(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody ActionLibraryInfoParam param, BindingResult result) {

        BaseRet<SearchUserInfoRet> ret = new BaseRet<SearchUserInfoRet>();

        try {

            checkParam(result);

            SearchUserInfoRet searchUserInfoRet = new SearchUserInfoRet();
            LpUserInfoTbl info = iUserService.selectUserInfo(param.getId());
            searchUserInfoRet.setHeader(info.getHeaderUrl());
            searchUserInfoRet.setNickname(info.getNickname());
            if (StringUtils.isNotEmpty(info.getSex())) {

                if (info.getSex().equals(Constant.sex.male)) {
                    searchUserInfoRet.setSex("男");
                } else if (info.getSex().equals(Constant.sex.female)) {
                    searchUserInfoRet.setSex("女");
                } else {
                    searchUserInfoRet.setSex("未知");
                }

            } else {
                searchUserInfoRet.setSex("未知");
            }
            searchUserInfoRet.setUsername(info.getUsername());
            searchUserInfoRet.setHeight(info.getHeight());
            searchUserInfoRet.setWeight(info.getWeight());

            //计算年龄
            if (StringUtils.isNotEmpty(info.getBirthday())) {
                long age = CommonFunctionUtil.CalculateTime(info.getBirthday() + " 12:00:00");
                searchUserInfoRet.setAge((int) age / 365);
            } else {
                searchUserInfoRet.setAge(0);
            }


            //扩展信息字段
            if (StringUtils.isNotEmpty(info.getExt())) {

                JSONObject ext = JSONObject.fromObject(info.getExt());

                if (ext.has("lastStoreName")) {
                    searchUserInfoRet.setLastStoreName(ext.getString("lastStoreName"));
                }
                if (ext.has("lastEntTime")) {
                    searchUserInfoRet.setLastEntTime(ext.getString("lastEntTime"));
                }
                if (ext.has("totalEntNum")) {
                    searchUserInfoRet.setTotalEntNum(ext.getInt("totalEntNum"));
                }
                if (ext.has("monthEntNum")) {
                    searchUserInfoRet.setMonthEntNum(ext.getInt("monthEntNum"));
                }

            } else {
                searchUserInfoRet.setLastEntTime("");
                searchUserInfoRet.setLastStoreName("");
                searchUserInfoRet.setTotalEntNum(0);
                searchUserInfoRet.setMonthEntNum(0);

            }

            //查询常去场馆名字
            LpStoreTbl storeInfo = iUserService.oftenGoStoreName(param.getId());
            if (storeInfo != null) {

                searchUserInfoRet.setStoreName(storeInfo.getStoreName());
            } else {
                searchUserInfoRet.setStoreName("");
            }

            //查询月卡情况
            UserMonthCardDto monthCard = iUserService.selectUserMonthCard(param.getId());
            if (monthCard != null) {

                searchUserInfoRet.setGoodsName(monthCard.getGoodsName());
                long day = 0;
                if (monthCard.getEndTime() != null) {
                    day = CommonFunctionUtil.calculateTime(monthCard.getEndTime());
                }

                if (day > 0) {
                    searchUserInfoRet.setMonthCard(day + "天");
                } else {
                    searchUserInfoRet.setMonthCard("已过期");
                }

            } else {
                searchUserInfoRet.setGoodsName("");
                searchUserInfoRet.setMonthCard("暂无月卡");
            }

            List<LpUserPropertyTbl> userProperty = iUserService.selectUserProperty(param.getId());
            if (userProperty != null && userProperty.size() > 0) {

                searchUserInfoRet.setGiveBalance(userProperty.get(0).getGiveBalance());
                BigDecimal rechargeBalance = userProperty.get(0).getAllBalance().subtract(userProperty.get(0).getGiveBalance());
                searchUserInfoRet.setRechargeBalance(rechargeBalance);

                if (userProperty.get(0).getIsDepositFree().equals("0")) {
                    searchUserInfoRet.setDepositInfo("免押");
                } else {

                    if (userProperty.get(0).getDeposit().compareTo(BigDecimal.ZERO) <= 0) {
                        searchUserInfoRet.setDepositInfo("未交押金");
                    } else {
                        searchUserInfoRet.setDepositInfo(userProperty.get(0).getDeposit() + "元");
                    }
                }


            } else {
                searchUserInfoRet.setRechargeBalance(BigDecimal.ZERO);
                searchUserInfoRet.setGiveBalance(BigDecimal.ZERO);
                searchUserInfoRet.setDepositInfo("未交押金");
            }

            //查询月卡消费次数
            int monthCardBuy = iUserService.selectUserBuyCardTotal(param.getId(), Constant.goodsType.monthCard);
            //查询次卡消费次数
            int dayCardBuy = iUserService.selectUserBuyCardTotal(param.getId(), Constant.goodsType.dayCard);

            searchUserInfoRet.setDayCardBuyTotal(dayCardBuy);
            searchUserInfoRet.setMonthCardBuyTotal(monthCardBuy);

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(searchUserInfoRet);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/setUserCard", method = RequestMethod.POST)
    @ApiOperation(notes = "设置用户月卡和押金", httpMethod = "POST", value = "设置用户月卡和押金")
    public BaseRet<String> setUserCard(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SetCardParam param, BindingResult result, HttpServletRequest request) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);

            if (iUserService.addUserCard(param.getId(), param.getRemark(), param.getShopId(), param.getCardDayNum())) {

                //记录日志
                iLoggerService.insert(getUserId(), Constant.logType.insert, "为用户id为：" + param.getId() + "的用户设置员工号，月卡" + param.getCardDayNum() + "天", CommonFunctionUtil.getClientIp(request));

                ret.setMsg("设置成功");
                ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);

            } else {

                ret.setMsg("设置失败");
                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            }


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/setReceive", method = RequestMethod.POST)
    @ApiOperation(notes = "设置用户已领取月卡奖励", httpMethod = "POST", value = "设置用户已领取月卡奖励")
    public BaseRet<String> setReceive(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody ActionLibraryInfoParam param, BindingResult result, HttpServletRequest request) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);
            LpUserInfoTbl info = iUserService.selectUserInfo(param.getId());
            LpUserInfoTbl lpUserInfoTbl = new LpUserInfoTbl();
            lpUserInfoTbl.setId(param.getId());

            if (StringUtils.isNotEmpty(info.getExt())) {

                JSONObject ext = JSONObject.fromObject(info.getExt());
                ext.put("isReceive", "1");
                lpUserInfoTbl.setExt(ext.toString());


            } else {

                JSONObject ext = new JSONObject();
                ext.put("isReceive", "1");
                lpUserInfoTbl.setExt(ext.toString());

            }

            if (iUserService.updateUserInfo(lpUserInfoTbl)) {

                //记录日志
                iLoggerService.insert(getUserId(), Constant.logType.insert, "为用户id为：" + param.getId() + "的用户领取月卡大礼包", CommonFunctionUtil.getClientIp(request));

                ret.setMsg("设置成功");
                ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);

            } else {

                ret.setMsg("设置失败");
                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            }


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/setMonthCard", method = RequestMethod.POST)
    @ApiOperation(notes = "用户月卡延期", httpMethod = "POST", value = "用户月卡延期")
    public BaseRet<String> setMonthCard(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SetCardParam param, BindingResult result, HttpServletRequest request) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);

            boolean flag = false;

            //查询当前用户的月卡
            UserMonthCardDto monthCard = iUserService.selectUserMonthCard(param.getId());

            if (monthCard != null) {

                //延期月卡
                LpUserGoodsTbl lpUserGoodsTbl = new LpUserGoodsTbl();
                //判断是否是已过期的月卡
                if (monthCard.getEndTime().getTime() < new Date().getTime()) {
                    lpUserGoodsTbl.setuEndTime(CommonFunctionUtil.getTimeToAfter(param.getCardDayNum(), CommonFunctionUtil.getDateTime(Constant.formatType.second)));
                } else {
                    lpUserGoodsTbl.setuEndTime(CommonFunctionUtil.getTimeToAfter(param.getCardDayNum(), monthCard.getEndTime()));
                }
                if (StringUtils.isNotEmpty(param.getRemark())) {
                    lpUserGoodsTbl.setRemark(param.getRemark());
                }
                flag = iUserService.updateUserGoodsByMonthCard(lpUserGoodsTbl, param.getId(), monthCard.getGoodsId());

            } else {

                //新增月卡
                LpUserGoodsTbl lpUserGoodsTbl = new LpUserGoodsTbl();
                //查询平台月卡
                List<LpGoodsTbl> goods = iGoodsService.selectGoodsByType(Constant.goodsType.monthCard);

                lpUserGoodsTbl.setuEndTime(CommonFunctionUtil.getTimeToAfter(param.getCardDayNum(), CommonFunctionUtil.getDateTime(Constant.formatType.second)));
                lpUserGoodsTbl.setGoodsId(goods.get(0).getId());
                lpUserGoodsTbl.setInserttime(CommonFunctionUtil.getDateTime(Constant.formatType.second));
                lpUserGoodsTbl.setRemark(param.getRemark());
                lpUserGoodsTbl.setState("0");
                lpUserGoodsTbl.setUserId(param.getId());

                flag = iUserService.insertUserGoods(lpUserGoodsTbl);
            }

            if (flag) {

                //记录日志
                iLoggerService.insert(getUserId(), Constant.logType.update, "为用户id为：" + param.getId() + "的用户延期月卡" + param.getCardDayNum() + "天", CommonFunctionUtil.getClientIp(request));

                ret.setMsg("设置成功");
                ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);

            } else {

                ret.setMsg("设置失败");
                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            }


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/monthCardTotal", method = RequestMethod.POST)
    @ApiOperation(notes = "用户月卡统计", httpMethod = "POST", value = "用户月卡统计")
    public BaseRet<MonthCardTotalRet> monthCardTotal(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody MonthCardTotalParam param, BindingResult result) {

        BaseRet<MonthCardTotalRet> ret = new BaseRet<MonthCardTotalRet>();

        try {

            checkParam(result);

            MonthCardTotalRet monthCardTotalRet = new MonthCardTotalRet();

            monthCardTotalRet.setExpired(iUserService.selectMonthCardTotal(1, param.getId()));
            monthCardTotalRet.setNotExpired(iUserService.selectMonthCardTotal(2, param.getId()));

            ret.setData(monthCardTotalRet);
            ret.setMsg("成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }
}
